import React, { useState, useEffect, useContext } from 'react';
import { ChatContentContext } from '@/pages/chat';
import { Tabs, DatePicker, Select, Button, Modal, Tag, Form,Divider  } from 'antd';
import { CloseOutlined, CalendarOutlined } from '@ant-design/icons';
import type { TabsProps } from 'antd';
import { useTranslation } from 'react-i18next';
import VisAttributionReport from '@/components/chat/chat-content/index-analysis/vis-attribution-report';
import VisForecastReport from '@/components/chat/chat-content/index-analysis/vis-forecast-report';
import AnalysisTable from './components/AnalysisTable';
import { modelGet, compareAnalysis, attributeAnalysis, predictAnalysis } from '@/client/api/workbenches';
const { RangePicker } = DatePicker;

interface FormValues {
    analysisDate: moment.Moment;
    compareDate: moment.Moment;
    dimension: string;
    forecastRange:[]
}

const MoreAnalysisSetting: React.FC = () => {
    const { t } = useTranslation();
    const { handleChat } = useContext(ChatContentContext);
    const [ activeTab, setActiveTab] = useState(1);
    const [ modelInfo, setModelInfo ] = useState([])
    const [ dimension, setDimension ] = useState([])  //模型下的所有表的 维度
    const [ metric, setMetric ] = useState('') // 度量
    const [ form ] = Form.useForm<FormValues>();
    const [ result, setResult ] = useState<any>(null);

    const tabItems: TabsProps['items'] = [
        { key: 1, label: t('year_on_year') },
        { key: 2, label: t('month_on_month') },
        { key: '归因分析', label: t('attribution') },
        { key: '预测分析', label: t('prediction') }
    ];

    // 发送消息给父页面
    const sendMessageToParent = (type,data: any) => {
        if (window.parent) {
            window.parent.postMessage({
                type: type,
                payload: data
            }, window.parent.location.origin);  
        }
    };

    // 监听父页面消息
    useEffect(() => {
        const handleMessage = async (event: MessageEvent) => {
            // 处理来自父页面的消息
            if (event.data.type === 'ANALYSIS_QUERY') {
                const modelId = event.data.payload.metricModelId;

                if (modelId) {                                 
                    setMetric(event.data.payload.metricColumnName)              
                    fetchModelInfo(modelId,{...event.data.payload});                
                }

                switch (event.data.payload.analysisType) {
                    case 'yoy':
                      setActiveTab(1);
                      break;
                    case 'mom':
                      setActiveTab(2);
                      break;
                    case 'attr':
                      setActiveTab('归因分析');
                      break;
                    case 'forecast':
                      setActiveTab('预测分析');
                      break;
                    default:
                        setActiveTab("预测分析");
                        break;
                }
            }
        };

        window.addEventListener('message', handleMessage);
        return () => window.removeEventListener('message', handleMessage);
    }, []);

    // useEffect(() => {
        const fetchModelInfo = async (modelId,params) => {  
            console.log('fetchModelInfo',modelId,params);       
            const res = await modelGet({ id: modelId });
            debugger;
            if (res?.data.data) {
              const dimensionList = [];
              const metricList = [];
              setModelInfo({
                ...res.data.data,
                predictStep: params.predictStep,
                predictStartTime: params.predictStartTime,
                predictEndTime: params.predictEndTime
            });
              res.data.data.metricModelTables?.forEach((table: any) => {   
                        
                  table.metricModelTableColumns.forEach((col: any) => {
                      if (col.metricType === 'Dimension') {
                          dimensionList.push({         
                              id: col.id,
                              comment: col.comment,
                              name: col.name,
                              tableId:col.tableId
                          });
                      }
                  });                  
              });
              
              setDimension(dimensionList);
            }         
        };    
    // }, []);

    // const submitSearch =async (values: FormValues) => {
    //     const message = {
    //         tab: activeTab,
    //         ...values,
    //         analysisDate: values.analysisDate?.format('YYYY-MM-DD'),
    //         compareDate: values.compareDate?.format('YYYY-MM-DD'),
    //         content: GenerateTxt(values)
    //     }
        
    //     sendMessageToParent('ANALYSIS_QUERY',message);
    // };

    const changeTab = (key: string | number) => {
        setActiveTab(key);
        setResult(null);
    }

    //  查询 
    const submitAnalysis = async (values: FormValues) => {
      const { compareDate, analysisDate } = values;
      const dimensionColumnList = []
      dimension && dimension.forEach(dim=>{
        values.dimension?.forEach(dimId=>{
          if(dim.id == dimId){
            dimensionColumnList.push({
                columnComment: dim.name,
                columnName: `${dim.tableId}:${dim.name}`
            })
          }
        })
      })

      const params =  {
          metricModelId: modelInfo.id,
          dateType: "D",
          metricColumnName: metric,
          compareType: activeTab,
          polymerizationMode: modelInfo.polymerizationMode,
          dimensionColumns: dimensionColumnList
      }

      if(activeTab <= 2){
        params.analysisDate = analysisDate?.format('YYYY-MM-DD');

        const res =await compareAnalysis(params);
        if(res.code ==0 && res.data.data.length){
          setResult(res.data)
        }
      }

      if(activeTab == '归因分析'){
        if (
            Array.isArray(compareDate) && compareDate[0] && compareDate[1] &&
            Array.isArray(analysisDate) && analysisDate[0] && analysisDate[1]
        ) {
            params.compareStartDate = compareDate[0].format('YYYY-MM-DD');
            params.compareEndDate = compareDate[1].format('YYYY-MM-DD');
            params.analysisStartDate = analysisDate[0].format('YYYY-MM-DD');
            params.analysisEndDate = analysisDate[1].format('YYYY-MM-DD');
            delete params.compareType;

            const res =await attributeAnalysis(params);
           
            if(res.data.data){          
              setResult(res.data.data)
            }
        }
      }

      if(activeTab == '预测分析'){
        if (
            Array.isArray(values.forecastRange) && values.forecastRange[0] && values.forecastRange[1]
        ) {
            params.startTime = values.forecastRange[0].format('YYYY-MM-DD');
            params.endTime = values.forecastRange[1].format('YYYY-MM-DD');
            params.predictStep = modelInfo.predictStep ?? 6;
            params.polymerizationMode = modelInfo.polymerizationMode;
            params.lostDateDealType = 2
            params.dateType = 'M'
            params.predictStartTime = modelInfo.predictStartTime;
            params.predictEndTime = modelInfo.predictEndTime
            
            delete params.compareType;
            delete params.dimensionColumns;

            const res =await predictAnalysis(params);
           
            if(res.data.data){          
              setResult(res.data.data)
            }
        }
      }
        
    }

    //根据不同的类型 生成不同的文本内容 去对话
    // const GenerateTxt = (formValues)=>{
    //     const { analysisDate, compareDate, dimension,forecastRange } = formValues;

    //     switch (activeTab) {
    //         case 1:    
    //             return `计算 时间：${compareDate.format('YYYY-MM-DD')}\n维度：${dimension.join(', ')}指标的同比`;
    //         break
    //         case 2:    
    //             return `计算 时间：${compareDate.format('YYYY-MM-DD')}\n维度：${dimension.join(', ')}指标的环比`;
    //         break
    //         case '归因分析':    
    //             return `查询 分析日期：${analysisDate.format('YYYY-MM-DD')}\n对比日期：${compareDate.format('YYYY-MM-DD')}\n维度：${dimension.join(', ')}的归因问题`;
    //         break
    //         case '预测分析':    
    //             return `计算${forecastRange[0].format('YYYY-MM-DD')} - ${forecastRange[1].format('YYYY-MM-DD')}时间的预测指标}`;
    //         break
    //     }
    // }

    return (
        <div className="flex-1 h-full p-6 w-full bg-white dark:bg-black overflow-y-auto">
            <div className="space-y-6">
                <div className="flex justify-between items-center mb-4">
                    <h2 className="text-lg font-medium">{t('i_more_analysis')}</h2>
                    <Button 
                        type="text" 
                        icon={<CloseOutlined />}
                        onClick={() => sendMessageToParent('CLOSE_ANALYSIS', {})}
                    />
                </div>
                
                <Tabs
                    items={tabItems}
                    activeKey={activeTab}
                    onChange={changeTab}
                />

                <Form
                    form={form}
                    layout="vertical"
                    onFinish={submitAnalysis}                  
                >
                
                    { activeTab === '归因分析' && (
                        <>
                            <Form.Item
                                label={t('i_analysis_date')}
                                name="analysisDate"
                                rules={[{ required: true, message: '请选择分析日期' }]}
                            >
                                <RangePicker />
                            </Form.Item>
                            <Form.Item
                                label={t('i_compare_date')}
                                name="compareDate"
                                rules={[{ required: true, message: '请选择对比日期' }]}
                            >
                                <RangePicker />
                            </Form.Item>
                        </>
                      )
                    }

                    { activeTab <= 2 && <Form.Item
                          label={t('log_time')}
                          name="analysisDate"
                          rules={[{ required: true, message: '请选择日期' }]}
                      >
                          <DatePicker
                              className="w-full"                         
                              suffixIcon={<CalendarOutlined />}
                          />
                      </Form.Item>
                    }

                    { activeTab !== '预测分析' && (
                        <>                        
                            <Form.Item
                                label={activeTab === '归因分析'? t('i_select_dimension') : t('i_dimension')}
                                name="dimension"
                            >
                                <Select
                                    className="w-full"
                                    mode="multiple"
                                    placeholder="请选择维度"
                                    fieldNames={{ label: 'comment', value: 'id' }}
                                    options={dimension}
                                />
                            </Form.Item>
                        </>
                    )}

                    { activeTab === '预测分析' && (
                        <Form.Item label={t('i_time_range')} name="forecastRange">   
                            <RangePicker />
                        </Form.Item>)
                    }

                    {/* 查询按钮 */}
                    <Form.Item className="text-center">
                        <Button
                            type="primary"
                            htmlType="submit"
                            className="w-32"
                        >
                            {t('w_query')}
                        </Button>
                    </Form.Item>
                </Form>
                <Divider  />

                { activeTab == 1 && <AnalysisTable activeType={activeTab} tableData={result} /> }

                { activeTab == 2 && <AnalysisTable activeType={activeTab} tableData={result} /> }

                { activeTab === '归因分析' && <VisAttributionReport dimData={result} />}

                { activeTab === '预测分析' && <VisForecastReport data={result} /> }

            </div>
        </div>
    );
};

export default MoreAnalysisSetting;